<template>
    <div>
        <div class="UnLogin" v-if="!isLogin">
            <p>登陆后使用常用地址</p>
            <p class="loginBtn" @click="goLogin">登录</p>
        </div>
        <div v-else>
            <div class="deliveryAdd">
                我的收货地址
            </div>
            <ul>
                <li v-for="(item,index) in addressList" class="addressItems" :key="index" @click="choosingAddress(item)">
                    <div class="addressIcon">
                        <i class='icon njfont nj-dizhi'></i>
                    </div>
                    <div class="itemContent">
                        <div style="display:flex;align-items:center;justify-content:space-between;">
                            <p style="text-align:left;color:#444;font-weight:bold;">收货人:{{item.receivername}}</p>
                            <p style="font-weight:bold;">{{item.inArea ? '' : '不在配送范围'}}</p>
                        </div>
                        <div class='specificAddress'>
                            <span class="typeTag" :style='`background:${labels[item.label].color}`'>{{labels[item.label].tag}}</span>
                            <span class="address">{{item.address}}{{item.houseNumber}}</span>
                        </div>
                    </div>
                    <div v-if='previousAddress && (previousAddress.addressid == item.addressid)' class="choosedIcon">
                        <i class='icon njfont nj-xuanzhong'></i>
                    </div>
                    <div v-else class="choosedIcon"></div>
                </li>
            </ul>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
import { mapGetters, mapActions } from 'vuex';
import { AddressSquence, GetUserInfo } from './axios';
import { NAVIGATE, CHOOSE_ADDRESS } from '../../../config/postMessage-types';
import getSearch from '../../../utils/getUrlSearch';
import { getHrefParams } from '../../../utils/zx';
import { Toast } from '../../../utils/toast';

export default {
    props:['choosePos'],
    data () {
        return {
            // reRender: false,
            // login: false,
            //lables&color
            labels: [
                {tag:'家庭',color:'deepskyblue'},
                {tag:'公司',color:'deepskyblue'},
                {tag:'其他',color:'deepskyblue'}
            ],
            previousAddress: {},
            addressList: []
        }
    },
    props: {
        getVaildStoreIdList: {
            type: Array,
            default: []
        }
    },
    components:{
        
    },
    computed:{
        ...mapGetters('wxh', [
            'userInfo'
        ]),
        ...mapGetters('qxz', [
            'getAddressList',
            'getAddressId',
            'getChoosedAddress'
        ]),
        isLogin() {
            return Object.keys(this.userInfo).length;
        },
        fromShopList() {
            return getHrefParams().fromShopList
        },
    },
    methods:{
        ...mapActions('qxz', [
            'updateAddressList',
            'updateChoosedAddress'
        ]),
        choosingAddress(item) {
            var url = api.tmsUrl + 'centralManagerApi/centralManagerObject';
            var data = {
                judgeInBaselatticeByStoreId: {
                    longitudeandlatitude: item.positionlng + ',' + item.positionlat,
                    storeIdList: this.getVaildStoreIdList
                }
            }
            var config = {
                url: url,
                method: "post",
                data
            }
            axios(config).then(res => {
                if(res.data.returnCode) {
                    this.sendAddToRn(item);
                    //临时的，防止从地图返回时丢失已选择的地址返回时
                    this.updateChoosedAddress(item)
                    localStorage.setItem('choosedAddress',JSON.stringify(item));
                    this.previousAddress = item;
                    this.$emit('previousAddress',item);
                }else {
                    Toast({
                        type: 'warn',
                        message: '该地址不在配送范围内'
                    })
                }
            })
        },
        // 是否再配送范围内
        async inAreaTest(item) {
            var url = api.tmsUrl + 'centralManagerApi/centralManagerObject';
            var data = {
                judgeInBaselatticeByStoreId: {
                    longitudeandlatitude: item.positionlng + ',' + item.positionlat,
                    storeIdList: this.getVaildStoreIdList
                }
            }
            var config = {
                url: url,
                method: "post",
                data
            }
            let res = await axios(config);
            if(Number(res.data.returnCode)) {
                return true
            }else {
                return false
            }
        },
        //发送地址给Rn
        sendAddToRn(obj) {
            obj.fromShopList = this.fromShopList
            let RnParams = {
                type: CHOOSE_ADDRESS,
                params: obj
            }
            window.postMessage(JSON.stringify(RnParams));
        },
        SaveAddress(params) {
            let sessionId = this.sessionId;
            let options = {
                url: api.customer_host + '/address',
                method:'POST',
                data: params,
                headers: {'sessionId': sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
            }
            return axios(options);
        },
        goLogin() {
            let goBackIns = {
                type: NAVIGATE,
                params: {
                    screen: 'Login',
                    params:{
                        FromWeb: true
                    }
                }
            }
            window.postMessage(JSON.stringify(goBackIns));
        },
        // 标记默认地址
        async signDefaultAddress(transferId) {
            let temper = await localStorage.getItem('choosedAddress');
            let temp = temper ? JSON.parse(temper) : null;
            var addressid = transferId || getSearch().addressid;
            if(temp){
                if(this.getChoosedAddress.addressid == -1 || addressid == -1) {
                    return
                }
                if(temp.addressid == this.getChoosedAddress.addressid || temp.addressid == addressid){
                    let inArea = await this.inAreaTest(temp);
                    if(inArea) {
                        this.previousAddress = temp;
                        this.$emit('previousAddress',temp);
                    }else {
                        this.$emit('previousAddress', 'scopeOut');
                    }
                }else {
                    let flag = 0
                    this.getAddressList.length && this.getAddressList.forEach(async ele => {
                        if(ele.addressid == addressid) {
                            let inArea = await this.inAreaTest(ele);
                            if(inArea) {
                                //临时的，防止从地图返回时丢失已选择的地址返回时
                                this.updateChoosedAddress(ele)
                                localStorage.setItem('choosedAddress',JSON.stringify(ele));
                                this.previousAddress = ele;
                                this.$emit('previousAddress',ele)
                                flag = 1
                            }
                        }
                    });
                    !flag && this.$emit('previousAddress', 'scopeOut');
                }
            }else {
                let flag = 0
                this.getAddressList.length && this.getAddressList.forEach(async ele => {
                    if(ele.addressid == addressid) {
                        let inArea = await this.inAreaTest(ele);
                        if(inArea) {
                            //临时的，防止从地图返回时丢失已选择的地址返回时
                            this.updateChoosedAddress(ele)
                            localStorage.setItem('choosedAddress',JSON.stringify(ele));
                            this.previousAddress = ele;
                            this.$emit('previousAddress',ele)
                            flag = 1
                        }
                    }
                });
                !flag && this.$emit('previousAddress', 'scopeOut');
            }
        },
    },
    async mounted(){
        var that = this;
        setTimeout(() => {
            that.signDefaultAddress();
        },300);
        let sessionId = getHrefParams().sessionId;
        this.login = sessionId;
        this.updateAddressList();
    },
    watch: {
        choosePos(newVal) {
            if(newVal){
                this.previousAddress = newVal;
            }
        },
        getAddressId(newVal) {
            if(newVal) {
                setTimeout(() => {
                    this.signDefaultAddress(newVal);
                },300)
            }
        },
        getAddressList(newVal) {
            let newAddList = [];
            this.getAddressList.map(async (ele, ind) => {
                let inArea = await this.inAreaTest(ele);
                ele.inArea = inArea
                newAddList.push(ele)
                if(newAddList.length === this.getAddressList.length) {
                    console.log('newAddList',this.getAddressList, newAddList)
                    this.addressList = newAddList;
                }
            })
        }
    }
}
</script>
<style scoped>
.UnLogin{
    width:100%;
    height:2rem;
    box-sizing: border-box;
    padding: 0 3%;
    background:white;
    display: flex;
    font-size: .9rem;
    /* line-height: 2.2rem; */
    align-items: center;
    justify-content: space-between;
}
.loginBtn{
    width: 2.4rem;
    height: 1.2rem;
    line-height: 1.2rem;
    border-radius: .2rem;
    border: 1px solid #80B760;
    color: #80B760;
}
.addressItems{
    width: 100%;
    min-height: 2.2rem;
    background: white;
    padding: .3rem 0;
    border-bottom: 1px solid #eaeaea;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.specificAddress{
    text-align: left;
    line-height: 1.2rem;
}
.itemContent{
    width: 75%;
    color: #9a9a9a;
}
.typeTag{
    padding: 0rem .1rem;
    color:white;
    border-radius:.1rem;
}
.addressIcon{
    width: 12%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.choosedIcon{
    color: rgb(116, 174, 86);
    width: 10%;
    height:100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.deliveryAdd{
    width: 100%;
    height: 1.8rem;
    line-height: 1.8rem;
    text-align: left;
    text-indent: .8rem;
    font-size: .8rem;
    color: #A3A3A3;
    border-top: 1px solid #EDEDED;
    border-bottom: 1px solid #EDEDED;
}
</style>